<template>
  <view class="order-list-container">
    <!-- 未登录状态 -->
    <view v-if="!isLogin" class="not-logged-in">
      <uni-icons type="person" size="100" color="#cccccc"></uni-icons>
      <text class="unlogin-text">登录后才能查看订单</text>
      <button class="btn-login" @click="goToLogin">去登录</button>
    </view>
    
    <!-- 已登录状态 -->
    <view v-else class="logged-in-container">
      <!-- 订单状态切换 -->
      <view class="status-tabs">
        <view 
          class="status-tab" 
          :class="{ active: currentStatus === item.value }" 
          v-for="item in statusTabs" 
          :key="item.value"
          @click="switchStatus(item.value)"
        >
          {{ item.label }}
        </view>
      </view>
    
    <!-- 订单列表 -->
    <scroll-view 
      class="order-list" 
      scroll-y="true" 
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
      refresher-background="#f5f5f5"
      refresher-default-style="black"
      style="width: 100%;"
    >
      <view class="order-item" v-for="(order, index) in orderList" :key="order.id" @click="goToDetail(order.id)">
        <view class="order-header">
          <text class="order-no">订单号：{{ order.orderNo }}</text>
          <text class="order-status" :class="'status-' + order.status">{{ order.statusText }}</text>
        </view>
        
        <view class="order-goods">
          <view class="goods-item" v-for="(goods, goodsIndex) in order.goods" :key="goodsIndex">
            <image :src="goods.image" class="goods-image"></image>
            <view class="goods-info">
              <text class="goods-name">{{ goods.name }}</text>
              <text class="goods-spec">{{ goods.spec }}</text>
              <view class="goods-price-section">
                <view class="price-info">
                  <text class="goods-original-price">¥{{ goods.originalPrice }}</text>
                  <text class="goods-price">¥{{ goods.price }}</text>
                  <text class="goods-unit">/{{ goods.unit }}</text>
                </view>
                <text class="goods-quantity">x{{ goods.quantity }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <view class="order-footer">
          <text class="order-time">{{ order.createTime }}</text>
          <view class="order-amount">
            <text class="amount-text">共{{ order.totalQuantity }}件商品 实付：</text>
            <text class="amount-value">¥{{ order.payAmount }}</text>
          </view>
        </view>
        
        <view class="order-actions" v-if="order.status === 1">
          <button class="action-btn cancel" @click.stop="cancelOrder(order.id)">取消订单</button>
          <button class="action-btn primary" @click.stop="payOrder(order.id)">立即付款</button>
        </view>
        
        <view class="order-actions" v-else-if="order.status === 3">
          <button class="action-btn" @click.stop="confirmReceive(order.id)">确认收货</button>
        </view>
      </view>
      
      <!-- 加载状态 -->
      <view class="load-more" v-if="orderList.length > 0">
        <text v-if="isLoading">加载中...</text>
        <text v-else-if="hasMore">上拉加载更多</text>
        <text v-else>没有更多数据了</text>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="orderList.length === 0 && !isLoading">
        <image src="/static/empty-order.png" class="empty-image"></image>
        <text class="empty-text">暂无{{ currentStatusText }}订单</text>
      </view>
    </scroll-view>
    </view>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      // 当前订单状态
      currentStatus: 'all',
      
      // 状态选项卡
      statusTabs: [
        { label: '全部', value: 'all' },
        { label: '待付款', value: 'unpaid' },
        { label: '待发货', value: 'unshipped' },
        { label: '待收货', value: 'shipped' },
        { label: '退款', value: 'refund' }
      ],
      
      // 订单列表
      orderList: [],
      
      // 分页参数
      page: 1,
      pageSize: 10,
      
      // 加载状态
      isLoading: false,
      isRefreshing: false,
      hasMore: true
    }
  },
  
  computed: {
    // 映射登录状态
    ...mapGetters(['getIsLogin']),
    
    // 登录状态
    isLogin() {
      return this.getIsLogin
    },
    
    // 当前状态文本
    currentStatusText() {
      const status = this.statusTabs.find(item => item.value === this.currentStatus)
      return status ? status.label : ''
    }
  },
  
  onLoad(options) {
    // 从路由参数获取订单状态
    if (options.type) {
      this.currentStatus = options.type
    }
    
    // 只有在已登录状态下才加载订单列表
    if (this.isLogin) {
      this.loadOrderList(true)
    }
  },
  
  onShow() {
    // 每次显示页面时检查登录状态
    // 如果从未登录变为已登录，则加载订单列表
    if (this.isLogin && this.orderList.length === 0) {
      this.loadOrderList(true)
    }
  },
  
  methods: {
    // 切换订单状态
    switchStatus(status) {
      if (this.currentStatus === status) return
      
      this.currentStatus = status
      this.page = 1
      this.hasMore = true
      this.loadOrderList(true)
    },
    
    // 加载订单列表
    loadOrderList(refresh = false) {
      if (refresh) {
        this.page = 1
        this.orderList = []
      }
      
      this.isLoading = true
      
      // 模拟API调用
      setTimeout(() => {
        const mockData = this.generateMockData()
        
        if (refresh) {
          this.orderList = mockData
        } else {
          this.orderList = [...this.orderList, ...mockData]
        }
        
        this.isLoading = false
        this.isRefreshing = false
        
        // 模拟没有更多数据
        if (this.page >= 3) {
          this.hasMore = false
        } else {
          this.page++
        }
      }, 1000)
    },
    
    // 生成模拟数据
    generateMockData() {
      const statusMap = {
        'all': [1, 2, 3, 4, 5],
        'unpaid': [1],
        'unshipped': [2],
        'shipped': [3],
        'refund': [4, 5]
      }
      
      const statusTextMap = {
        1: '待付款',
        2: '待发货',
        3: '待收货',
        4: '退款中',
        5: '已退款'
      }
      
      // 参考首页和购物车的商品数据
      const productData = [
        {
          id: 201,
          name: '兴宁手打猪肉丸',
          originalPrice: 5999,
          discountPrice: 4999,
          unit: '斤',
          image: 'https://pic.rmb.bdstatic.com/bjh/video/46cace1e2cb2827fc520fbc6769ebef5.jpeg'
        },
        {
          id: 202,
          name: '自家做的仙人板',
          originalPrice: 149,
          discountPrice: 99,
          unit: '碗',
          image: 'https://qcloud.dpfile.com/pc/Z1XbyrAyCWz1qqscp3gTNrC2EIqbevu6XaPpnfpH4cyOy49x-iCOD4mvVJcr1l6I.jpg'
        },
        {
          id: 203,
          name: '自家晒的猪肉干',
          originalPrice: 399,
          discountPrice: 299,
          unit: '斤',
          image: 'https://pic.rmb.bdstatic.com/bjh/241216/dump/279b49f325fde86015838cea70e4db79.jpeg'
        },
        {
          id: 204,
          name: '自家做的肉肠',
          originalPrice: 499,
          discountPrice: 399,
          unit: '斤',
          image: 'https://img0.baidu.com/it/u=3364154920,628749022&fm=253&app=138&f=JPEG?w=500&h=500'
        }
      ]
      
      const allowedStatus = statusMap[this.currentStatus] || statusMap['all']
      
      return Array.from({ length: 5 }, (_, i) => {
        const status = allowedStatus[Math.floor(Math.random() * allowedStatus.length)]
        const goodsCount = Math.floor(Math.random() * 3) + 1
        const goods = Array.from({ length: goodsCount }, (_, j) => {
          const product = productData[j % productData.length]
          return {
            id: product.id,
            name: product.name,
            spec: `规格：${['大份', '中份', '小份'][j % 3]}`,
            price: (product.discountPrice / 100).toFixed(2),
            originalPrice: (product.originalPrice / 100).toFixed(2),
            quantity: Math.floor(Math.random() * 3) + 1,
            unit: product.unit,
            image: product.image
          }
        })
        
        const totalQuantity = goods.reduce((sum, item) => sum + item.quantity, 0)
        const totalAmount = goods.reduce((sum, item) => sum + (item.price * item.quantity), 0).toFixed(2)
        
        return {
          id: `order_${this.page}_${i}`,
          orderNo: `202310${String(Math.floor(Math.random() * 100000)).padStart(5, '0')}`,
          status,
          statusText: statusTextMap[status],
          createTime: `2023-10-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')} ${String(Math.floor(Math.random() * 24)).padStart(2, '0')}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}`,
          goods,
          totalQuantity,
          totalAmount,
          payAmount: totalAmount,
          freight: '10.00'
        }
      })
    },
    
    // 加载更多
    loadMore() {
      if (this.isLoading || !this.hasMore) return
      this.loadOrderList()
    },
    
    // 下拉刷新
    onRefresh() {
      this.isRefreshing = true
      this.loadOrderList(true)
      
      // 确保刷新状态正确重置
      setTimeout(() => {
        this.isRefreshing = false
      }, 2000) // 设置一个合理的超时时间，防止刷新状态卡住
    },
    
    // 跳转到订单详情
    goToDetail(orderId) {
      uni.navigateTo({
        url: `/pages/order/detail?id=${orderId}`
      })
    },
    
    // 取消订单
    cancelOrder(orderId) {
      uni.showModal({
        title: '提示',
        content: '确定要取消该订单吗？',
        success: (res) => {
          if (res.confirm) {
            // 这里应该调用API取消订单
            uni.showToast({
              title: '订单已取消',
              icon: 'success'
            })
            
            // 刷新订单列表
            this.loadOrderList(true)
          }
        }
      })
    },
    
    // 支付订单
    payOrder(orderId) {
      // 这里应该调用API支付订单
      uni.showToast({
        title: '正在跳转支付...',
        icon: 'loading'
      })
      
      setTimeout(() => {
        uni.showToast({
          title: '支付成功',
          icon: 'success'
        })
        
        // 刷新订单列表
        this.loadOrderList(true)
      }, 1500)
    },
    
    // 确认收货
    confirmReceive(orderId) {
      uni.showModal({
        title: '提示',
        content: '确认已收到商品吗？',
        success: (res) => {
          if (res.confirm) {
            // 这里应该调用API确认收货
            uni.showToast({
              title: '已确认收货',
              icon: 'success'
            })
            
            // 刷新订单列表
            this.loadOrderList(true)
          }
        }
      })
    },
    
    // 去登录
    goToLogin() {
      uni.navigateTo({
        url: '/pages/login/login'
      })
    }
  }
}
</script>

<style>
.order-list-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
  overflow: hidden; /* 防止容器溢出 */
}

.not-logged-in {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 0 40rpx;
}

.logged-in-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.unlogin-text {
  font-size: 30rpx;
  color: #999;
  margin: 40rpx 0 60rpx 0;
}

.btn-login {
  background-color: #e93b3d;
  color: #fff;
  border-radius: 10rpx;
  font-size: 32rpx;
}

.status-tabs {
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 0;
  z-index: 10;
  height: 100rpx; /* 设置固定高度 */
  flex-shrink: 0; /* 防止压缩 */
}

.status-tab {
  flex: 1;
  text-align: center;
  padding: 30rpx 0;
  font-size: 28rpx;
  color: #666;
  position: relative;
}

.status-tab.active {
  color: #e93b3d;
  font-weight: bold;
}

.status-tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background-color: #e93b3d;
  border-radius: 2rpx;
}

.order-list {
  flex: 1;
  height: 0; /* 重要：设置高度为0，让flex: 1生效 */
  overflow: hidden; /* 防止内容溢出 */
}

.order-item {
  background-color: #fff;
  border-radius: 16rpx;
  margin: 24rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  box-sizing: border-box; /* 确保宽度计算包含内边距和边框 */
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 24rpx;
  border-bottom: 1px solid #f5f5f5;
}

.order-no {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.order-status {
  font-size: 28rpx;
  font-weight: 500;
}

.status-1 {
  color: #fa2c19;
}

.status-2 {
  color: #ff976a;
}

.status-3 {
  color: #1989fa;
}

.status-4, .status-5 {
  color: #07c160;
}

.order-goods {
  padding: 30rpx 24rpx;
}

.goods-item {
  display: flex;
  padding: 24rpx 0;
}

.goods-item:not(:last-child) {
  border-bottom: 1px solid #f5f5f5;
}

.goods-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  margin-right: 24rpx;
  background-color: #f7f7f7;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-name {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
  line-height: 1.4;
  margin-bottom: 12rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.goods-spec {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 16rpx;
}

.goods-price-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-info {
  display: flex;
  align-items: baseline;
}

.goods-original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
  margin-right: 12rpx;
}

.goods-price {
  font-size: 32rpx;
  color: #fa2c19;
  font-weight: bold;
}

.goods-unit {
  font-size: 24rpx;
  color: #999;
  margin-left: 4rpx;
}

.goods-quantity {
  font-size: 28rpx;
  color: #666;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 24rpx;
  border-top: 1px solid #f5f5f5;
}

.order-time {
  font-size: 26rpx;
  color: #999;
}

.order-amount {
  display: flex;
  align-items: center;
}

.amount-text {
  font-size: 26rpx;
  color: #666;
}

.amount-value {
  font-size: 32rpx;
  color: #fa2c19;
  font-weight: bold;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  padding: 24rpx 24rpx 30rpx;
  border-top: 1px solid #f5f5f5;
}

.action-btn {
  margin-left: 16rpx;
  padding: 16rpx 32rpx;
  font-size: 28rpx;
  border-radius: 40rpx;
  background-color: #fff;
  border: 1px solid #ddd;
  color: #666;
  line-height: 1.2;
  min-width: 140rpx;
  text-align: center;
  box-sizing: border-box;
}

.action-btn.primary {
  background-color: #e93b3d;
  color: #fff;
  border-color: #e93b3d;
}

.action-btn.cancel {
  border-color: #999;
}

.load-more {
  text-align: center;
  padding: 40rpx 0;
  font-size: 28rpx;
  color: #999;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
}

.empty-image {
  width: 240rpx;
  height: 240rpx;
  margin-bottom: 40rpx;
}

.empty-text {
  font-size: 30rpx;
  color: #999;
}
</style>